<template>
  <a-card class="table-card">
    <!-- 吸顶： 返回列表 / 智能读取 / 保存草稿 按钮项 -->
    <a-affix offsetTop="0">
      <div style="display: flex; justify-content: space-between; line-height: 60px; background-color: white;">
        <a-button style="line-height: 60px;" type="text" @click="emits('switchApplyPage', { page: 'list' })">
          <left-outlined />返回列表页
        </a-button>
        <div style="font-weight: bold; margin-left: 30px;"> {{ vdata.isDetail ? '活动详情' : vdata.isAdd ? '创建活动' : '修改活动' }} </div>
        <div style="width: 150px; display: flex; align-items: center; justify-content:space-evenly">
          <!-- <a-tooltip placement="left" title="保存草稿将不验证数据的合法性">
            <a-button type="primary " @click="saveDataFunc(true)">
              <save-outlined /> 保存草稿
            </a-button>
          </a-tooltip> -->
          <a-button :style="{ cursor: vdata.isDetail ? 'not-allowed' : 'pointer' }" type="primary " @click="saveDataFunc(true)">
            <save-outlined /> 保存草稿
          </a-button>
        </div>
      </div>
      <a-divider style="margin: 0" />
    </a-affix>

    <!-- 引入具体的接口组件  -->
    <component :is="vdata.currentComponent" ref="activityComponentRef" :isDetail="vdata.isDetail" />

    <!-- 底部操作项 -->
    <a-affix :offset-bottom="20">
      <div style="background-color: white;">
        <a-divider style="margin: 0; margin-top: 20px;" />

        <div class="bottom-buttons">
          <div class="bottom-buttons-item" @click="emits('switchApplyPage', { page: 'list' })">
            <a-button type="link" style="color: #808080 ;">
              <left-outlined />返回列表页
            </a-button>
          </div>
          <div style="width: 1px; height: 100%; background-color: #f0f0f0;" />
          <div class="bottom-buttons-item" @click="saveDataFunc(false)">
            <a-button :style="{ cursor: vdata.isDetail ? 'not-allowed' : 'pointer' }" type="link">
              创建活动 <send-outlined />
            </a-button>
          </div>
        </div>
      </div>
    </a-affix>
  </a-card>
</template>
<script setup lang="ts">
import { req, API_URL_ACTIVITY_DETAILS, $activityAddOrEdit } from '@/api/manage'
import { ref, reactive, getCurrentInstance, defineEmits, inject, provide, computed, watch } from 'vue'
import { useUserStore } from '@/store/modules/user'
import activityTemplateMap from './activityTemplateMap.js'
import activityBasicInfoDefault from './activityBasicInfoDefault.js'
import dayjs from 'dayjs'
import { activityConfig } from './activityConfig.js'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const activityComponentRef = ref()

// list页面的 切换页面的函数
const emits = defineEmits(['switchApplyPage'])

// 参数注入： 创建的活动模板数据（包含 模板编号 模板名称 ） 【  当修改操作时：  列表页面需要查询出进件信息，并provice该信息 】 
let activityTemplateDataRef : any = inject('activityTemplateData')
let activityTemplateData : any = activityTemplateDataRef.value

// 向子组件注入： 创建活动具体参数
provide('activityDetailInfo', computed(() => vdata.activityDetailInfo))

// 当前页面的对象信息
const vdata: any = reactive({
  title:'',//页面标题
  isAdd: false, // 是否是新增
  isDetail: false, // 是否是详情页
  butLoading:false,//进度条
  currentComponent: null,
  activityDetailInfo: { //创建活动详细参数
    activitySetting: {
      mchType: 1,  // 参与商户类型
      isFirstJoinScore: 0,  // 首次参与奖励
      isEveryJoinScore: 0,  // 每次参与奖励
      overType: 0, // 奖品过期类型
      awardType: 0, // 中奖概率设置
      // awardPeriodType: 0, // 奖品派发周期性次数限制
      // 下面是之前用户限制合并过来的
      timeStartEnd: [],
      isOnlyOneTimes: 0,
      periodType: 0,
      specialType: 0,
      timeType: 0,

      // 下面是新增字段
      hasBlacklist: 0,
      hasWhitelist: 0,
      thresholdType: 0,
      isFollowOfficial: 1,
    },
    activityAwardList: [], // 奖品列表
    activityShare: {
      shareSuccessStandard: 0,  // 分享成功标准
      sharePeriodType: 0, // 同一用户周期性分享次数限制类型
      toSharePeriodType: 0, // 同一用户周期性助力次数限制类型
      exchangeType:0,//奖品兑换类型
    }
  },
})

// 提供activityShare是否变化
const activityShareChangeRef = ref(false)
provide('activityShareChange', activityShareChangeRef)
// 监听activityShare是否发生变化
watch(() => vdata.activityDetailInfo.activityShare, (newVal, oldVal) => {
  if(!activityShareChangeRef.value){
    activityShareChangeRef.value = true
  }
}, { deep: true })

// 页面渲染函数
async function pageRender({ isAdd, activityDetail, isDetail }) {
  vdata.isAdd = isAdd
  vdata.isDetail = isDetail
  // 把模版对应基础信息默认值 合并到活动数据中
  if(vdata.isAdd){
    Object.assign(vdata.activityDetailInfo, activityBasicInfoDefault[activityTemplateData.activityTemplateNo])
  }
  myGlobalLoadingFunc(true)
  // 根据模板编号  动态引入组件 
  if(!vdata.isAdd){ // 修改 从详情中获取模板信息
    activityTemplateData.activityTemplateNo = activityDetail.activityTemplateNo
    // 拉取详情并赋值到 activityDetailInfo
    await fetchActivityDetail(activityDetail.activityId, activityDetail.activityTemplateNo)
  }
  import(`./templates/${activityTemplateMap[activityTemplateData.activityTemplateNo]}.vue`).then((module) => {
    vdata.currentComponent = module.default
  })
  vdata.title=getTitle()
}

/**
 * 拉取活动详情数据 并处理数据
 * @param activityId 活动ID
 * @param activityTemplateNo 模板编号
 */
async function fetchActivityDetail(activityId, activityTemplateNo) {
  const result = await req.list(API_URL_ACTIVITY_DETAILS, { activityId, activityTemplateNo })
  Object.assign(vdata.activityDetailInfo, JSON.parse(JSON.stringify(result)))
  const { startTime, endTime, entryway, activitySetting = {} } = vdata.activityDetailInfo
  const { onlyOneTimes, specialType, specialContent, timeType, timeStart, timeEnd, firstJoinScore, everyJoinScore } = activitySetting
  // activityBasicInfo处理
  vdata.activityDetailInfo.activityTime = (startTime && endTime) ? [startTime, endTime] : []
  vdata.activityDetailInfo.entryway = entryway ? entryway.split(',') : []
  // activitySetting处理
  activitySetting.isOnlyOneTimes = onlyOneTimes === 0 ? 0 : 1
  activitySetting.specialContent = (specialType !== 0 && specialContent) ? specialContent.split(',') : []
  activitySetting.timeStartEnd = (timeType === 1 && timeStart && timeEnd) ? [timeStart, timeEnd] : null
  activitySetting.isFirstJoinScore = firstJoinScore ? 1 : 0
  activitySetting.isEveryJoinScore = everyJoinScore ? 1 : 0
}

/**
 * 进度条
 * @param isShowGlobalLoadingVal 
 */
 function myGlobalLoadingFunc(isShowGlobalLoadingVal) {
  useUserStore().setGlobalLoading(isShowGlobalLoadingVal)
}

function getTitle() {
  return '创建活动'
}


// 保存数据
function saveDataFunc(isDraft) {
  // 判断是否是详情页
  if (vdata.isDetail) return
  // 校验数据合法性
  activityComponentRef.value.saveDataPreCallback(isDraft).then(async () => {
    // 进度条
    myGlobalLoadingFunc(true)
    const METHOD = vdata.isAdd ? 'POST' : 'PUT'
    const payload:any = {
      ...JSON.parse(JSON.stringify(vdata.activityDetailInfo)),
      entryway: vdata.activityDetailInfo.entryway ? vdata.activityDetailInfo.entryway.join(',') : '',
      payAuthId: vdata.activityDetailInfo.payAuthId ? vdata.activityDetailInfo.payAuthId : null,
      activityTemplateNo: activityTemplateData.activityTemplateNo,
      state: isDraft ? 0 : 1,
    }
    if(vdata.isAdd){
      payload.activityNo = `ACNO${dayjs().format('YYYYMMDDHHmmss')}`
    }
    // activitySetting 数据处理--------------------------------------------------------------第二步
    const { activitySetting = {} } = payload
    if (activitySetting.isOnlyOneTimes === 0 || !activitySetting.onlyOneTimes) {
      activitySetting.onlyOneTimes = 0
    }
    if(activitySetting.periodType === 0 || !activitySetting.periodTimes){
      activitySetting.periodTimes = 0
    }
    if (activitySetting.specialType !== 0 && activitySetting.specialContent) {
      activitySetting.specialContent = activitySetting.specialContent.join(',')
    } else {
      delete activitySetting.specialContent
    }
    if (activitySetting.timeType === 1 && activitySetting.timeStartEnd) {
      activitySetting.timeStart = activitySetting.timeStartEnd[0]
      activitySetting.timeEnd = activitySetting.timeStartEnd[1]
    } else {
      delete activitySetting.timeStart
      delete activitySetting.timeEnd
    }
    if(activitySetting.isFirstJoinScore == 0 || !activitySetting.firstJoinScore){
      activitySetting.firstJoinScore = 0
    }
    if(activitySetting.isEveryJoinScore == 0 || !activitySetting.everyJoinScore){
      activitySetting.everyJoinScore = 0
    }
    // 模板不包含活动分享配置表单 或者 没有修改活动分享配置 则不传activityShare数据
    if(!activityConfig.activityShare.usedTemplate.includes(activityTemplateData.activityTemplateNo) || !activityShareChangeRef.value){
      delete payload.activityShare
    }
    $activityAddOrEdit(METHOD, payload).then(() => {
      $infoBox.message.success('创建成功')
      // 返回列表页
      emits('switchApplyPage', { page: 'list', params: { refresh: vdata.isAdd ? true : false } })
    }).finally(() => {
      myGlobalLoadingFunc(false)
    })
  }).catch((e) => {
  })
}

defineExpose({ pageRender })

</script>
<style  lang="less" scoped>
.bottom-buttons {
  display: flex;
  flex-direction: row;
  justify-content: center;
  height: 60px;

  .bottom-buttons-item {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .bottom-buttons-item:hover {
    transition: 0.3s ease;
    background-color: rgba(23, 91, 230, 0.05);
    cursor: pointer;
  }

}

.content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: left;
  padding: 10px;
}
</style>
